package com.jyx.govern.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.jyx.framework.model.response.CommonCode;
import com.jyx.framework.model.response.ResponseResult;
import com.jyx.govern.gateway.service.AuthService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginFilter extends ZuulFilter {

    @Autowired
    AuthService authService;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
       // HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
       /* String authorization = request.getHeader("Authorization");
        System.out.println(authorization);*/
        String access_token = authService.getTokenFromCookie(request);

        //cookie身份令牌  redis身份令牌时间  jwt身份令牌  缺一不可
        if(access_token == null){
            access_denied();
        }
        long expire = authService.getExpire(access_token);
        if(expire<=0){
            access_denied();
        }
        String jwt = authService.getJwtFromHeader(request);
        if(jwt == null){
            access_denied();
        }
        return null;
    }

    /**
     * 拒绝访问
     */
    private void access_denied(){
        RequestContext currentContext = RequestContext.getCurrentContext();
        currentContext.setSendZuulResponse(false);
        ResponseResult responseResult = new ResponseResult(CommonCode.UNAUTHENTICATED);
        String jsonString = JSON.toJSONString(responseResult);
        currentContext.setResponseBody(jsonString);
        currentContext.setResponseStatusCode(200);
        HttpServletResponse response = currentContext.getResponse();
        response.setContentType("application/json;charset=utf-8");

    }
}
